package it.localhost.deepthought.one.service;

import it.localhost.deepthought.one.common.DatabaseHelper;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;

public class ArtificialIntelligence {
	private static final String even = "8642";
	private static final String odd = "7531";

	public static int[] getMove(Activity context, String input, boolean aiOdd, int level) {
		Cursor cur = new DatabaseHelper(context).getMoves(input, aiOdd);
		int[] move;
		if (Math.random() <= cpuPower(level) && cur.getCount() > 0) {
			cur.moveToPosition((int) (Math.random() * cur.getCount()));
			move = new int[] { cur.getInt(0), cur.getInt(1) };
		} else {
			ArrayList<int[]> listGood = new ArrayList<int[]>();
			ArrayList<int[]> listBad = new ArrayList<int[]>();
			for (byte i = 0; i < 8; i++)
				for (byte j = (byte) (i + 1); j < 8; j++)
					if (input.charAt(i) < input.charAt(j)) {
						int[] is = new int[] { i, j };
						StringBuilder out = new StringBuilder();
						for (int k = 0; k < 8; k++)
							if (k != is[0] && k != is[1])
								out.append(input.charAt(k));
							else if (k == is[0])
								out.append(input.charAt(is[1]));
							else if (k == is[1])
								out.append(input.charAt(is[0]));
						int win = whoWin(out.toString());
						if ((win == 1 && aiOdd) || (win == -1 && !aiOdd))
							listBad.add(is);
						else
							listGood.add(is);
					}
			move = listGood.size() != 0 ? listGood.get((int) (Math.random() * listGood.size())) : listBad.get((int) (Math.random() * listBad.size()));
		}
		cur.close();
		return move;
	}

	public static boolean noMoves(Activity context, String input, boolean aiOdd, int level) {
		return Math.random() < cpuPower(level) && new DatabaseHelper(context).getMoves(input, aiOdd).getCount() == 0;
	}

	/**
	 * 
	 * @param move
	 * @return 0 for drow, 1 for win even, -1 for odd win, 2 for nobody win
	 */
	public static int whoWin(String move) {
		StringBuilder evenSb = new StringBuilder();
		StringBuilder oddSb = new StringBuilder();
		for (byte l = 0; l < 8; l++) {
			byte temp = (byte) (move.charAt(l) - '0');
			if ((temp % 2) == 0)
				evenSb.append(temp);
			else
				oddSb.append(temp);
		}
		String evenFromMove = evenSb.toString();
		String oddFromMove = oddSb.toString();
		if (evenFromMove.equals(even) && oddFromMove.equals(odd))
			return 0;
		else if (evenFromMove.equals(even))
			return 1;
		else if (oddFromMove.equals(odd))
			return -1;
		else
			return 2;
	}

	private static double cpuPower(int i) {
		return Math.sqrt(i) / 25 + 0.6;
	}
}